package com.soccerlover.strictfield.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author hck soccerlover9527@gmail.com
 */
public class ReflectUtil {

    /**
     * 获取所有的 {@link Field}
     * 如果需要获取到父类,则会递归获取父级的 field. 直到 Object
     *
     * @param clazz              目标类 class 对象
     * @param includeSupperClass 是否获取父类
     * @return list of fields
     */
    public static List<Field> getAllFields(Class<?> clazz, boolean includeSupperClass) {
        ArrayList<Field> fields = new ArrayList<>();
        if (includeSupperClass) {
            getAllSupperClassFields(clazz, fields);
        }
        Collections.addAll(fields, clazz.getDeclaredFields());
        return fields;
    }

    /**
     * 递归获取父类 fields 直到 {@link Object} 为止,不包括 Object
     *
     * @param targetObj  目标 class
     * @param fieldsList 存放field
     */
    private static void getAllSupperClassFields(Class<?> targetObj, List<Field> fieldsList) {
        Class<?> superclass = targetObj.getSuperclass();
        if (!superclass.equals(Object.class)) {
            Collections.addAll(fieldsList, superclass.getDeclaredFields());
            getAllSupperClassFields(superclass, fieldsList);
        }
    }
}
